package com.xundao.yxt.controller;

import com.xundao.yxt.common.util.ResultUtils;
import com.xundao.yxt.common.vo.base.ResponseVo;
import com.xundao.yxt.domain.model.User;
import com.xundao.yxt.domain.service.BizCategoryService;
import com.xundao.yxt.domain.service.PermissionService;
import com.xundao.yxt.domain.service.SysConfigService;
import com.xundao.yxt.domain.service.UserService;
import io.springboot.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;

import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@Controller
@AllArgsConstructor
public class SystemController {
    private final UserService userService;
    private final PermissionService permissionService;
    private final BizCategoryService bizCategoryService;
    private final SysConfigService configService;

    /**
     * 访问登录
     *
     * @param model
     */
    @GetMapping("/login")
    public ModelAndView login(Model model) {
        ModelAndView modelAndView = new ModelAndView();
        if (SecurityUtils.getSubject().isAuthenticated()) {
            modelAndView.setView(new RedirectView("/admin", true, false));
            return modelAndView;
        }
        modelAndView.setViewName("system/login");
        return modelAndView;
    }
    @PostMapping("/login")
    @ResponseBody
    public ResponseVo login(HttpServletRequest request, String username, String password, String verification,
                            @RequestParam(value = "rememberMe", defaultValue = "0") Integer rememberMe) {
        //判断验证码
        if (!CaptchaUtil.ver(verification, request)) {
            // 清除session中的验证码
            CaptchaUtil.clear(request);
            return ResultUtils.error("验证码错误！");
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            token.setRememberMe(1 == rememberMe);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
        } catch (LockedAccountException e) {
            token.clear();
            return ResultUtils.error("用户已经被锁定不能登录，请联系管理员！");
        } catch (AuthenticationException e) {
            token.clear();
            return ResultUtils.error("用户名或者密码错误！");
        }
        //更新最后登录时间
        userService.updateLastLoginTime((User) SecurityUtils.getSubject().getPrincipal());
        return ResultUtils.success("登录成功！");
    }

}
